package com.cskaoyan.duolai.clean.gateway.filter;


import cn.hutool.core.util.IdUtil;
import com.cskaoyan.duolai.clean.gateway.properties.ApplicationProperties;
import com.cskaoyan.duolai.clean.gateway.utils.GatewayWebUtils;
import com.cskaoyan.duolai.clean.common.constants.ErrorInfo;
import com.cskaoyan.duolai.clean.common.constants.HeaderConstants;
import com.cskaoyan.duolai.clean.common.model.CurrentUserInfo;
import com.cskaoyan.duolai.clean.common.utils.Base64Utils;
import com.cskaoyan.duolai.clean.common.utils.JsonUtils;
import com.cskaoyan.duolai.clean.common.utils.JwtTool;
import com.cskaoyan.duolai.clean.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;


/**
 * token解析过滤器
 */
@Slf4j
@Component
public class TokenFilter implements GlobalFilter {

    /**
     * token header名称
     */
    private static final String HEADER_TOKEN = "Authorization";

    // 注入关于登录白名单
    @Resource
    private ApplicationProperties applicationProperties;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 获取请求的uri
        String uri = GatewayWebUtils.getUri(exchange);

        List<String> accessPathWhiteList = applicationProperties.getAccessPathWhiteList();

        if(accessPathWhiteList.contains(uri)){
            // uri在白名单里，直接放行
            return chain.filter(exchange);
        }

        // 获取HEADER_TOKEN中的登录信息
        String token = GatewayWebUtils.getRequestHeader(exchange, HEADER_TOKEN);

        if(StringUtils.isEmpty(token)){
            return GatewayWebUtils.toResponse(exchange,HttpStatus.FORBIDDEN.value(), ErrorInfo.Msg.REQUEST_FORBIDDEN);
        }

        Integer userType = JwtTool.getUserType(token); // 获取用户类型
        String tokenSecret = applicationProperties.getTokenKey().get(userType + ""); //获取相应用户类型的秘钥
        if(StringUtils.isEmpty(tokenSecret)){
            return GatewayWebUtils.toResponse(exchange,HttpStatus.FORBIDDEN.value(), ErrorInfo.Msg.REQUEST_FORBIDDEN);
        }

        //  拿到用户的登录信息，转发给服务 framework 中mvc/interceptor
        JwtTool jwtTool = new JwtTool(tokenSecret);
        CurrentUserInfo currentUserInfo = jwtTool.parseToken(token);
        String userInfoJson = JsonUtils.toJsonStr(currentUserInfo);
        String encodeStr = Base64Utils.encodeStr(userInfoJson);

        ServerWebExchange newExchange = GatewayWebUtils.setRequestHeader(exchange, HeaderConstants.USER_INFO, encodeStr);


        // 4.请求放行
        return chain.filter(newExchange);
    }
}
